package com.sn.author.filter.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sn.author.common.annotation.Advice;
import com.sn.author.common.enums.ExceptionEnum;
import com.sn.author.common.exception.BadRequestException;
import com.sn.author.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonInputMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * Request for conduct params encrypt
 */
@Component
@ControllerAdvice(basePackages = "com.sn.author.controller")
@Slf4j
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {
    

    /**
     * If return false. any request not adopt this. use true express request will enter interceptor
     * @param methodParameter Method's params string .
     * @param type            Type
     * @return  Pass-check
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        Advice advice = methodParameter.getParameterAnnotation(Advice.class);
        return advice == null || advice.need();
    }

    /**
     * Send controller before interceptor operation
     * @return Data after decryption
     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        try {
            //Encrypted string
            Object encrypted = parserParams(httpInputMessage);
            if(encrypted == null){
                return null;
            }
            log.info(">>>>> Raw encrypted param info: {}",encrypted);
            String ecnStr = JSON.parseObject(encrypted.toString()).getString("data");
            String decode = decodeParams(ecnStr);
            log.info("<<<<< DecodeRequestBodyAdvice decode params info: {}",decode);

            if (Objects.equals("error", decode)) {
                log.error(">>>>> Failed to decrypt request header data <<<<<");
                //Decryption failed
                throw new BadRequestException(ExceptionEnum.PARAMS_DECRYPT_ERR);
            }
            return new MappingJacksonInputMessage(new ByteArrayInputStream(decode.getBytes(StandardCharsets.UTF_8)),httpInputMessage.getHeaders());
        }  catch (Exception e){
            log.error("Unusual execution decryption !!!!! {}",e.getMessage());
        }
        return null;
    }

    private String decodeParams(Object encrypted) {
        if(encrypted == null){
            return "error";
        }
        try {
            String decode =  AESUtil.desEncrypt(encrypted.toString());
            if(decode == null){
                return "error";
            }
            return decode;
        } catch (Exception e) {
            return "error";
        }
    }

    private Object parserParams(HttpInputMessage httpInputMessage) {
        return parserWebParams(httpInputMessage);
    }

    private String parserWebParams(HttpInputMessage httpInputMessage) {

        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader;
        JSONObject paramsObj;

        try {
            InputStream inputStream = httpInputMessage.getBody();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }

            //Original request params
            paramsObj = JSON.parseObject(stringBuilder.toString());
            if(paramsObj == null){
                return null;
            }
            return paramsObj.toJSONString();
        }catch (Exception e){
            log.error("Parser WEB request params failed. message:[{}]",e.getMessage());
            log.error("Throw exception stack: \n" );
            throw new BadRequestException("Parser request params failed.");
        }
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return null;
    }
}
